import Taro from "@tarojs/taro";
import { useState, useEffect, useLayoutEffect } from "react";
import Loading from "../../myComponent/load";
import Main from "../main";
import Utils from "@/utils/index";
import { getStorage } from "@/pages/components/utils";
import { getBaseUrl, requestSystemUrl } from "@/network/baseUrl";
import { HttpGet, HttpPost } from "@/network/servers";
import { useDispatch } from "react-redux";
import { useDocumentTitle, useOnlineCheck } from "@/utils/myUtils";
import useNavLoginPage from "../../../hooks/useNavLoginPage";
import './index.scss'

const storage = getStorage();

function App() {
  const [init, setInit] = useState(false);
  const dispatch = useDispatch();
  useNavLoginPage({}, "/pages/messagePushSetting/index");
  useDocumentTitle("消息中心推送设置");

  const getToken = () => {
    if (Utils.getQueryVariable("env") === "weapp") {
      return Utils.getQueryVariable("lg_tk");
    } else {
      return storage.get("token") || Utils.getQueryVariable("lg_tk");
    }
  };

  // 获取初始数据
  const getCommonData = (params) => {
    Taro.getSysWeb({ sysId: "000", eduId: Utils.getQueryVariable("eduId") },"web",
      function (res) {
        dispatch({ type: "SET_MAINSERVER", data: res });
        let MainServerAddr = res;
        HttpGet({
          url: "/api/commons/users/info",
          data: {
            token: params.lg_tk,
          },
        }).then((result) => {
          let userInfo = result.data;
          let userIdentityList = userInfo?.userIdentityList || [];
          let currentIdentity =
            userIdentityList.find((i) => i.identityCode) ||
            userIdentityList[0] ||
            {};

          dispatch({
            type: "SET_IDENTITYCODE",
            data: currentIdentity?.identityCode || "",
          });

          let messageId = "210";

          if (userInfo.eduId) {
            dispatch({
              type: "SET_ISEDU",
              data: true,
            });
            messageId = "211";
            userInfo.schoolId = userInfo.eduId;
          }

          useOnlineCheck(MainServerAddr, params.lg_tk, messageId);
          HttpGet({
            url: "/api/commons/schools/school/details",
            data: {
              schoolId: userInfo.schoolId,
            },
          }).then(({data:response}) => {
            // userInfo["schoolLevel"] = response.schoolLevel;
            // userInfo["schoolType"] = response.schoolType;

            dispatch({ type: "SET_USERINFO", data: userInfo });

            // 模块权限校验
            // HttpPost({
            //     url:MainServerAddr+'/UserMgr/PowerMgr/ValidateIdentity',
            //     data:{
            //         IdentityCode:currentIdentity.identityCode,
            //         ModuleID:''
            //     }
            // })
            setInit(true);
          });
        });
      }
    );
  };

  useEffect(() => {
    let params = {} as any;
    if (process.env.TARO_ENV === "h5") {
      if (Utils.getQueryVariable("env") === "weapp") {
        //内嵌进h5的页面
        dispatch({ type: "SET_ENV", data: "weapp" });

        requestSystemUrl("210").then((res) => {
          window.baseUrl = res;
          params = {
            lg_tk: Utils.getQueryVariable("lg_tk") || storage.get("lg_tk"),
            lg_ic: Utils.getQueryVariable("lg_ic"),
            env: Utils.getQueryVariable("env"),
            schoolId: Utils.getQueryVariable("schoolId"),
            baseUrl: res,
          };
          dispatch({ type: "SET_BASEURL", data: res });
          dispatch({ type: "SET_TOKEN", data: getToken() });
          getCommonData(params);
        });
      } else {
        window.baseUrl = getBaseUrl();
        dispatch({ type: "SET_ENV", data: "app" });
        dispatch({ type: "SET_BASEURL", data: getBaseUrl() });
        params = {
          lg_tk: storage.get("lg_tk") || Utils.getQueryVariable("lg_tk"),
          lg_ic: Utils.getQueryVariable("lg_ic") || storage.get("lg_ic"),
          baseUrl: getBaseUrl(),
        };
        dispatch({ type: "SET_TOKEN", data: getToken() });
        getCommonData(params);
      }
    } else {
      //小程序部分（可忽略，目前不使用此方案）
      dispatch({ type: "SET_ENV", data: "weapp" });
      dispatch({ type: "SET_BASEURL", data: getBaseUrl() });
      params = {
        lg_tk: storage.get("lg_tk"),
        lg_ic: storage.get("lg_ic"),
        baseUrl: getBaseUrl(),
      };
      getCommonData(params);
    }
  }, []);

  if (!init) {
    return <Loading />;
  }

  return <Main />;
}
export default App;
